<template>
  <div>
    <el-breadcrumb separator="/" style="margin-bottom: 20px;">
      <el-breadcrumb-item :to="{ path: '/' }">商家信息</el-breadcrumb-item>
      <el-breadcrumb-item>商户管理</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
      <!-- 搜索 -->
      <el-form ref="SellerFormRef" :model="SellerForm" label-width="120px">
        <el-row>
          <el-col :lg="8" :md="12" :sm="12" :xs="24">
            <el-form-item label="店铺名">
              <el-input
                v-model="SellerForm.shopname"
                placeholder="请输入"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="5" style="text-align: right;">
            <el-button type="primary" @click="search">搜索</el-button>
            <el-button @click="reset">重置</el-button>
          </el-col>
          <el-col :span="11" style="text-align: right;">
            <el-button @click="addDialog" type="warning">添加商户</el-button>
          </el-col>
        </el-row>
      </el-form>

      <!-- 表格 -->
      <el-table
        :data="sellerData"
        border
        :header-cell-style="{ 'text-align': 'center' }"
        style="width: 100%;"
      >
        <el-table-column
          type="index"
          label="序号"
          align="center"
          width="50"
        ></el-table-column>
        <el-table-column
          v-for="(item, index) in tableColumn"
          :key="index"
          :prop="item.prop ? item.prop : undefined"
          :label="item.label"
          align="center"
          :width="item.width"
        >
          <template slot-scope="scope">
            <div v-if="item.type === 'role'">
              {{ scope.row[item.prop] | role }}
            </div>
            <img
              v-if="item.type === 'img'"
              :src="scope.row[item.prop]"
              alt=""
              style="width: 150px; height: 120px;"
            />
            <div v-else-if="item.type === 'date'">
              {{ scope.row[item.prop] | timeFilter }}
            </div>
            <div v-else>{{ scope.row[item.prop] }}</div>
          </template>
        </el-table-column>

        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button @click="editDialog(scope.row)" type="text" size="small"
              >编辑</el-button
            >
            <el-button @click="delClick(scope.row)" type="text" size="small"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-row style="text-align: right;">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageNum"
          :page-sizes="[5, 10, 15, 20]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        ></el-pagination>
      </el-row>
    </el-card>
    <!-- 弹框 -->
    <el-dialog
      title="提示"
      :visible.sync="dialogVisible"
      width="35%"
      :before-close="handleClose"
    >
      <el-form
        :model="addFormRef"
        :rules="rules"
        ref="addFormRef"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="商户名称" prop="shopname">
          <el-input
            v-model="addFormRef.shopname"
            placeholder="请输入商户名称"
            style="width: 100%;"
          >
          </el-input>
        </el-form-item>
        <el-form-item label="商家地址" prop="address">
          <el-input v-model="addFormRef.address"
          placeholder="请输入地址"></el-input>
        </el-form-item>
        <el-form-item label="开店日期" prop="opShopTime">
        <el-date-picker
         v-model="addFormRef.opShopTime"
         align="right"
         type="date"
         placeholder="选择日期">
        </el-date-picker>
        </el-form-item>
        <el-form-item label="责任人" prop="seller">
          <el-input v-model="addFormRef.seller" 
          
          placeholder="请输入责任人"></el-input>
        </el-form-item>
         <el-form-item label="电话号码" prop="phone">
          <el-input v-model="addFormRef.phone"

          placeholder="请输入电话号码"></el-input>
        </el-form-item>
        <!--  :action="`${BASEURL}:5000/api/Seller/upload`" -->
        <el-form-item label="营业执照" prop="sellerImg">
            <el-upload
         
            class="upload-demo"
            drag
            action="fake"
            :http-request="uploadSectionFile" 
            accept=".jpg,.png,.pdf,.word"
            :before-upload="beforeUpload"
            :limit="1"
            :on-success="onSucess"
            :on-error="onError"
            :on-change="uploadImage"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :file-list="fileList"
          >
             <i class="el-icon-upload"></i>
             <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
             <div class="el-upload__tip" slot="tip">支持jpg、png、pdf、word格式，大小不超过500M。</div>
          </el-upload>
        </el-form-item>
        <el-form-item>
        <el-button @click="resetClick">取&nbsp消</el-button>
        <el-button type="primary" @click="submitForm('addFormRef')">确&nbsp定</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { mapState } from "vuex";
import { axios } from "axios";
const tableColumn = [
  { label: "商铺名", prop: "shopname", type: "text" },
  { label: "商铺地址", prop: "address", type: "text" },
  { label: "责任人", prop: "seller", type: "text" },
  { label: "开店日期", prop: "opShopTime", type: "date" },
  { label: "营业执照", prop: "sellerImg", type: "img", width: 200 },
  { label: "联系电话", prop: "phone", type: "text" }
];
export default {
  data() {
    return {
          addFormRef: {
          shopname: '',
          address: '',
          seller: '',
          opShopTime: '',
          sellerImg: '',
          phone:''
        },
      SellerForm: {},
      sellerData: [],
      fileList: [],
      BASEURL: "http://localhost:5000",
      rules: {
      shopname: [
          { required: true, message: "请输入商铺名称", trigger: "blur" }
        ],
        address: [{ required: true, message: "请输入地址", trigger: "blur" }],
        seller: [{ required: true, message: "责任人", trigger: "blur" }],
        opShopTime: [{ required: true, message: "请输入开店日期", trigger: "change" }],
        phone: [{ required: true, message: "请输入联系电话", trigger: "blur" },
        {
            validator: function(rule, value, callback) {
              if (
                /^(?:(?:\+|00)86)?1(?:(?:3[\d])|(?:4[5-7|9])|(?:5[0-3|5-9])|(?:6[5-7])|(?:7[0-8])|(?:8[\d])|(?:9[1|8|9]))\d{8}$/.test(
                  value
                ) == false
              ) {
                callback(new Error("请输入正确的手机号码"));
              } else {
                callback();
              }
            },
            trigger: "blur"
          }],
        sellerImg: [{ required: true, message: "请上传营业执照", trigger: "change"  }],
      },
      currentPage: 5,
      total: 0,
      pageSize: 5,
      pageNum: 1,
      tableColumn,
      dialogVisible: false
    };
  },
  mounted() {
    this.getList();
  },
  methods: {
    getList() {
      this.SellerForm.pageSize = this.pageSize;
      this.SellerForm.pageNum = this.pageNum;
      this.$api
        .get("/api/seller/list", { params: this.SellerForm })
        .then(res => {
          this.sellerData = res.data.data.records;
          this.total = res.data.data.total;
        })
        .catch(err => {
          console.log(err);
          this.$message.error("获取列表失败");
        });
    },
    search() {
      this.pageNum = 1;
      this.getList();
    },
    reset() {
      this.pageNum = 1;
      this.SellerForm = {};
      this.getList();
    },
    handleSizeChange(pageSize) {
      this.pageSize = pageSize;
      this.pageNum = 1;
      this.getList();
    },
    handleCurrentChange(pageNum) {
      this.pageNum = pageNum;
      this.getList();
    },
    // 添加
    addDialog() {
      this.addFormRef = {};
      this.dialogVisible = true;
    },
    // 编辑
    editDialog(row) {
      this.addFormRef = row;
      this.dialogVisible = true;
    },
    // 关闭按钮
    handleClose() {
      this.$confirm("确认关闭？")
        .then(_ => {
          // 重置清空表单
          this.$refs.addFormRef.resetFields();
          this.resetClick();
        })
        .catch(_ => {});
    },
    // 提交为空时不调用接口
    submitForm(formName) {
        this.$refs[formName].validate((valid) => {
              if (valid) {
              if (this.addFormRef._id) {
        this.$api
          .post(`/api/seller/edit/${this.addFormRef._id}`, this.addFormRef)
          .then(res => {
            this.addFormRef = {};
            this.dialogVisible = false;
            this.getList();
             this.$message({
                type: "success",
                message: "编辑成功!"
              });
          });
      } else {
        this.$api.post(`/api/seller/add`, this.addFormRef).then(res => {
          this.addFormRef = {};
          this.dialogVisible = false;
          this.getList();
           this.$message({
                type: "success",
                message: "添加成功!"
              });
        });
      }
          } else {
            this.$message({
                type: "warning",
                message: "请先添加数据!"
              });
            return false;
          }
        });
    },
    // onsucess时的回调
    onSucess(response,file,fileList){
    },
    onError(err, file, fileList){
    },
    // 重置按钮
    resetClick() {
      this.$refs.addFormRef.resetFields();
      this.dialogVisible = false;
    },
    // 删除
    delClick(row) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.$api
            .delete(`/api/seller/delete/${row._id}`)
            .then(res => {
              this.$message({
                type: "success",
                message: "删除成功!"
              });
              this.pageNum = 1;
              this.getList();
            })
            .catch(err => {
              this.$message({
                type: "error",
                message: "删除失败"
              });
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    // 上传前校验
    beforeUpload(file,fileList) {
      const limitSize = 500;
      const isLt500M = file.size / 1024 / 1024 < limitSize;
      if (!isLt500M) {
      this.$message.error(`上传文件大小不能超过 ${limitSize}MB!`);
        }
        return isLt500M;
      },
    // 取消上传
    handleRemove(file, fileList) {
    },
    // 回显
    handlePictureCardPreview(file) {
    },

    // http-request
     uploadSectionFile(params) {
          const file = params.file,
            fileType = file.type,
            isLt500M = file.size / 1024 / 1024 < 500;
          // // 这里常规检验，看项目需求而定
          if (!isLt500M) {
            this.$message.error("只能上传图片大小小于500M");
            return;
          }
          // 根据后台需求数据格式
          const form = new FormData();
         
          // 文件对象
          form.append("file", file);
           this.imageUpload(form)
            .then(res => {
             //自行处理各种情况
              const status = res && parseInt(res.status, 10);
              console.log(res,"res")

              if (status=== 200) {
                this.$message.success('上传成功')
                const path=res.data[0].path
                this.addFormRef.sellerImg=path
                // console.log(this.addFormRef.sellerImg,"11111111111111")
              } else {
                this.$message.warning('超过最大规定大小！')
              }
            })
            .catch((res) => {
            console.log(res,"res")
            });
    },
    // 封装
    imageUpload (param){
      const url = "/api/seller/upload"
      return this.$api.post(url,param,{ 
      })
    },

    // 上传
      uploadImage(file, fileList) {
      if (file.response) {
          var windowURL = window.URL || window.webkitURL;
          this.src=windowURL.createObjectURL(file.raw);
        // 创建地址来展示文件地址
        console.log(this.addFormRef.sellerImg)
        this.addFormRef.sellerImg = file.response[0].path;
        const pathImage=file.response[0].path
        // 上传给表单
        this.param=new FormData();
        this.param.append('file',file.raw,file.name)
      }
    },
  }
};
</script>

<style></style>
